package com.example.purchase.view.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.example.purchase.R;
import com.example.purchase.bean.BaseBean;
import com.example.purchase.bean.DataBean;
import com.example.purchase.databinding.ActivityLoginBinding;
import com.example.purchase.network.RetrofitClient;
import com.example.purchase.network.service.HttpService;
import com.example.purchase.view.base.BaseActivity;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class LoginActivity extends BaseActivity<ActivityLoginBinding> implements View.OnClickListener {

    private String user,pass;
    private final HttpService service = RetrofitClient.getInstance().getService(HttpService.class);
    private SharedPreferences sp;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEmpty() {

    }

    @Override
    protected void initClick() {
        dataBinding.btnSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                onSwitch(isChecked);
            }
        });
        dataBinding.send.setOnClickListener(this);
        dataBinding.loginButton.setOnClickListener(this);
    }

    @Override
    protected void initTimeOut() {

    }

    //切换按钮
    private void onSwitch(boolean isChecked) {
        if (isChecked){
            dataBinding.authority.setText(R.string.login_gray_admin);
            dataBinding.username.setHint(R.string.edit_mi_yue);
            dataBinding.pass.setHint(R.string.edit_pass);
            dataBinding.fontSwitch.setText(R.string.switch_admin);
            dataBinding.send.setVisibility(View.GONE);
        }else {
            dataBinding.authority.setText(R.string.login_gray);
            dataBinding.username.setHint(R.string.edit_phone);
            dataBinding.pass.setHint(R.string.edit_qrcode);
            dataBinding.fontSwitch.setText(R.string.switch_user);
            dataBinding.send.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send:
                //首先判断手机号
                user = String.valueOf(dataBinding.username.getText());
                Pattern pattern = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$");
                Matcher matcher = pattern.matcher(user);
                if (!matcher.matches()) {
                    dataBinding.usernameError.setVisibility(View.VISIBLE);
                    break;
                }

                dataBinding.usernameError.setVisibility(View.GONE);
                dataBinding.sendText.setVisibility(View.GONE);
                dataBinding.number.setVisibility(View.VISIBLE);
                CountDownTimer timer = new CountDownTimer(60000, 1000) {
                    public void onTick(long millisUntilFinished) {
                        dataBinding.number.setText(millisUntilFinished / 1000 + "秒后重发");
                    }

                    public void onFinish() {
                        dataBinding.sendText.setVisibility(View.VISIBLE);
                        dataBinding.number.setVisibility(View.GONE);
                        dataBinding.send.setClickable(true);
                    }
                };

                Log.e("TAG", "onClick: " + user);
                service.sendCode(user).subscribe(new Consumer<BaseBean<List<DataBean>>>() {
                    @Override
                    public void accept(BaseBean<List<DataBean>> listBaseBean) throws Throwable {
                        Log.e("TAG", "短信发送成功: " + listBaseBean.getCode() + listBaseBean.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        Log.e("TAG", "短信发送失败: " + throwable);
                    }
                });
                dataBinding.send.setClickable(false);
                timer.start();
                break;
            case R.id.login_button:
                pass = String.valueOf(dataBinding.pass.getText());
                if (dataBinding.btnSwitch.isChecked()){
                    user = String.valueOf(dataBinding.username.getText());
                    if (pass.isEmpty() || user.isEmpty()){
                        Toast.makeText(this, "请输入账户和密钥", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    service.loginAdmin(user,pass).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).filter(new Predicate<BaseBean<String>>() {
                        @Override
                        public boolean test(BaseBean<String> stringBaseBean) throws Throwable {
                            dataBinding.passError.setVisibility(View.VISIBLE);
                            return String.valueOf(stringBaseBean.getCode()).equals("200");
                        }
                    }).subscribe(new Consumer<BaseBean<String>>() {
                        @Override
                        public void accept(BaseBean<String> stringBaseBean) throws Throwable {
                            dataBinding.passError.setVisibility(View.GONE);
                            sp = getSharedPreferences("userMessage", Context.MODE_PRIVATE);
                            sp.edit().putString("role", String.valueOf(dataBinding.btnSwitch.isChecked())).apply();
                            sp.edit().putString("token", stringBaseBean.getData()).apply();
                            startActivity(new Intent(LoginActivity.this,MainActivity.class));
                            finish();
                        }
                    });
                }else {
                    if (pass.isEmpty()){
                        Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    service.loginUser(user,pass).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).filter(new Predicate<BaseBean<String>>() {
                                @Override
                                public boolean test(BaseBean<String> stringBaseBean) throws Throwable {
                                    dataBinding.passError.setVisibility(View.VISIBLE);
                                    return String.valueOf(stringBaseBean.getCode()).equals("200");
                                }
                            }).subscribe(new Consumer<BaseBean<String>>() {
                        @Override
                        public void accept(BaseBean<String> stringBaseBean) throws Throwable {
                            dataBinding.passError.setVisibility(View.GONE);
                            sp = getSharedPreferences("userMessage", Context.MODE_PRIVATE);
                            sp.edit().putString("phone",user).apply();
                            sp.edit().putString("token",stringBaseBean.getData()).apply();
                            sp.edit().putString("role", String.valueOf(dataBinding.btnSwitch.isChecked())).apply();
                            startActivity(new Intent(LoginActivity.this,MainActivity.class));
                            finish();
                        }
                    });
                }
                break;
        }
    }
}